<?php


namespace app\api\services;

use app\common\libs\Singleton;
use app\common\models\Cart\Cart;
use app\common\models\Cart\MemberCart;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

class CartService
{
    use Singleton;

    public function delCart($goodsCart,$userId): bool
    {
        foreach ($goodsCart as $v){
            $where = [
                ['user_id', '=', $userId],
                ['goods_id', '=', $v['goodsId']],
                ['sku_id', '=', $v['skuId']],
            ];
            MemberCart::getInstance()->where($where)->update(['deleted' => 1]);
        }
        return true;
    }

    /**
     * @param $userId
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function cartList($userId): array
    {
        $where = [
            ['user_id', '=', $userId],
            ['deleted', '=', 0],
        ];
        $cartList = Cart::getInstance()->where($where)->order('shop_id desc')->select();
        return empty($cartList) ? [] : $cartList->toArray();

    }

    /**
     * 购物车信息
     * @param $userId
     * @param $goodsId
     * @param $skuId
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function cartInfo($userId, $goodsId, $skuId): array
    {
        $where = [
            ['user_id', '=', $userId],
            ['goods_id', '=', $goodsId],
            ['sku_id', '=', $skuId],
            ['deleted', '=', 0],
        ];
        $info = Cart::getInstance()->where($where)->find();
        return empty($info) ? [] : $info->toArray();
    }

}